package tsing.javase.thread.pool;

import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.*;

public class MultiFutrures {


    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ExecutorService service = Executors.newFixedThreadPool(20);
        ArrayList<Future> futures = new ArrayList<>(); //list 集合保存线程执行结果
        for (int i = 0; i < 20; i++) {
            Future<Integer> future = service.submit(new CallableTask()); //执行线程
            futures.add(future);
        }
        Thread.sleep(5000);
        for (Future future : futures) {
            System.out.println(future.get()); //
        }

        service.shutdown(); //关闭线程池
    }

    static class CallableTask implements Callable<Integer> {
        @Override
        public Integer call() throws Exception {
            Thread.sleep(1000);
            return new Random().nextInt();
        }
    }


    public void method(){
        // 创建单线程-线程池，任务依次执行
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(2, 2,
                60, TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(2),
                new ThreadPoolExecutor.CallerRunsPolicy());

        for (int i = 0; i < 10; i++) {
            //创建任务
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(20);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName());
                }
            };
            // 将任务交给线程池管理
            threadPoolExecutor.execute(runnable);
        }

        threadPoolExecutor.shutdown();//结束线程池


    }





}
